package com.example.yiwei.crm.view.activity.JYCoordingActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.dockDao;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.dockDaoImpl;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.data.GetExchange;
import com.example.yiwei.crm.entity.ExchangeEntity;
import com.example.yiwei.crm.entity.JLfsEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.json.JLfsJson;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;
import com.example.yiwei.crm.view.Class.listviewClass.CoorSelectAdapter;
import com.example.yiwei.crm.view.activity.jdjycooractivity.JYJDAddManyiduActivity;
import com.example.yiwei.crm.view.activity.jtCustomer.JDcoorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;




public class JYAddJLActivity extends AppCompatActivity {
    private TextView add_jl;
    private EditText tv_jll,tv_pj;
    private Spinner sp_jl_fs;
    String str;
    private String time;
    private List<managerEntity> managerList = new ArrayList<>();
    private Button button;
    private List<String> name_list=new ArrayList<>();
    private SharedPreferences sp;
    private ArrayAdapter adapter1,adapter2;
    private String managerName,fs_name;
    private int  manager_id,fs_id;
    private List<JLfsEntity> fslist;
    private List<String> fs_list = new ArrayList<>();
    private int dock_id;
    private ExchangeEntity entity;
    private Date date1,date2;
    private ArrayAdapter adapter3;
    JSONObject object1;
    List<com.example.yiwei.crm.entity.dockingEntity> coorlist= new ArrayList<>();
    private List<String> coor_name_list = new ArrayList<>();
    String coorname;
    private double jd,wd;
    private String address;
    int coor_id;
    private Button button1;
    private RelativeLayout coor_rl;
    private ImageView img_back;
    private ImageView img_search,img_luru,img_me,img_tj;
    private ImageView img_coor_select;
    private PopupWindow mPopWindow;
    private EditText edit_search;
    private Button btn_search;
    private ListView listView;
    private CoorSelectAdapter adapter;
    private String msg;
    private TextView show_coor;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jyadd_jl);
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        show_coor = (TextView) findViewById(R.id.show_coor_name);
        img_coor_select = (ImageView) findViewById(R.id.img_xiangxia);
        img_luru= (ImageView) findViewById(R.id.item_image_lr);
        img_search= (ImageView) findViewById(R.id.item_image_cx);
        img_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(JYAddJLActivity.this,JDcoorActivity.class);
                intent.putExtra("ii","ii");
                startActivity(intent);
                finish();
            }
        });
        img_luru.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(JYAddJLActivity.this,JDcoorActivity.class);
                startActivity(intent);
                finish();
            }
        });
        img_back= (ImageView) findViewById(R.id.add_jl_img_back);
        tv_jll = (EditText) findViewById(R.id.add_jl_jiaoliuliang);
        img_tj= (ImageView) findViewById(R.id.item_image_tj);
        img_me= (ImageView) findViewById(R.id.item_image_w);
        tv_pj  = (EditText) findViewById(R.id.add_jl_requred);
        sp_jl_fs = (Spinner) findViewById(R.id.add_jl_bf_fs);
        button1 = (Button) findViewById(R.id.add_jl_btn);
        add_jl = (TextView) findViewById(R.id.healt_education_add_txt_title);
        tv_jll.setInputType(InputType.TYPE_CLASS_NUMBER);
        coor_rl = (RelativeLayout) findViewById(R.id.add_jl_coor_rl);
        dock_id = getIntent().getIntExtra("dockid",0);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if ("update".equals(getIntent().getStringExtra("tag"))){
            setMessage();
            coor_rl.setVisibility(View.GONE);
        }
        img_me.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(JYAddJLActivity.this,JDcoorActivity.class);
                intent.putExtra("me","me");
                startActivity(intent);
                finish();
            }
        });
        img_tj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(JYAddJLActivity.this,JDcoorActivity.class);
                intent.putExtra("tt","tt");
                startActivity(intent);
                finish();
            }
        });
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener( myListener );
        initLocation(); //设置定位参数
        mLocationClient.start(); // 开始定位
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
////                result= NetWorkUtils.getCount(baseClass.find_visit_spinner_url,null);
////                dockDao dockDao=new dockDaoImpl();
////                YXJBSpinnerList=dockDao.queryDockingSpinnerMessage(result,1);
////                ZTSpinnerList=dockDao.queryDockingSpinnerMessage(result,2);
//                SC sc = new SC();
//                JSONObject object = sc.storage(sp);
//                String json1 = object.toString();
//                dockDao dockDao = new dockDaoImpl();
//                coorlist = dockDao.queryAllCoordinationMessage(baseClass.find_coordination_url + 1, json1);
//                try {
//                    object.put("admin",sp.getString("admin",null));
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                String json = object.toString();
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (coorlist != null) {
//                            for (int i3 = 0; i3 < coorlist.size(); i3++) {
//                                if (coorlist.get(i3).getDocking_mechanism()!=null&&!coorlist.get(i3).getDocking_mechanism().equals("")){
//                                    coor_name_list.add(coorlist.get(i3).getDocking_mechanism()+"-"+coorlist.get(i3).getDocking_name());
//                                }else{
//                                    coor_name_list.add(coorlist.get(i3).getDocking_name());
//                                }
//                            }
//                            adapter2 = new ArrayAdapter(JYAddJLActivity.this, R.layout.spinner_display_style, R.id.txtvwSpinner, coor_name_list);
//                            adapter2.setDropDownViewResource(R.layout.spinner_dropdown_style);
//                            spinner_coor.setAdapter(adapter2);
//                            spinner_coor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                                @Override
//                                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                                    coorname = coorlist.get(position).getDocking_name();
//                                    coor_id = coorlist.get(position).getDocking_id();
//                                }
//
//                                @Override
//                                public void onNothingSelected(AdapterView<?> parent) {
//
//                                }
//                            });
//                            if ("update".equals(getIntent().getStringExtra("tag"))) {
//                                for (int i = 0; i < coorlist.size(); i++) {
//                                    if (coorlist.get(i).getDocking_id() == entity.getCoor_id()) {
//                                        spinner_coor.setSelection(i);
//                                    }
//                                }
//                            }
//                        }
//                    }
//
//
//                });
//            }
//        }).start();
        img_coor_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SC sc = new SC();
                        JSONObject object = sc.storage(sp);
                        String json = object.toString();
                        dockDao dockDao = new dockDaoImpl();
                        coorlist = dockDao.queryAllCoordinationMessage(baseClass.find_coordination_url + 1, json);
                        if (coorlist!=null) {
                            Log.d("ccc", coorlist.size() + "");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (coorlist != null) {
                                        adapter = new CoorSelectAdapter(JYAddJLActivity.this, coorlist);
                                        showPopupWindow();
                                    }
                                }
                            });
                        }else{
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(JYAddJLActivity.this, "没有合作客户，请新建合作客户！", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                try {
                    object.put("admin",sp.getString("admin",null));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                managerDao manaDao=new managerDaoImpl();
                managerList=manaDao.queryAllManager(baseClass.query_manager_url,json);
                JSONObject object1 = sc.storage(sp);
                String json1 = object1.toString();
                String result = NetWorkUtils.getCount(baseClass.find_bf_fs_sp_URL,json1);
                fslist = JLfsJson.get(result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i2=0;i2<managerList.size();i2++){
                            name_list.add( managerList.get(i2).getManager_name());
                        }
                        adapter1 = new ArrayAdapter(JYAddJLActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, name_list);
                        adapter1.setDropDownViewResource(R.layout.spinner_dropdown_style);

                        for (int i3 = 0;i3<fslist.size();i3++){
                            fs_list.add(fslist.get(i3).getName());
                        }
                        adapter2 = new ArrayAdapter(JYAddJLActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, fs_list);
                        adapter2.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        sp_jl_fs.setAdapter(adapter2);
                        sp_jl_fs.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                fs_name = fslist.get(position).getName();
                                fs_id = fslist.get(position).getId();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        if ("update".equals(getIntent().getStringExtra("tag"))){
                            entity = GetExchange.exchangeEntity;
                            for (int i = 0;i<name_list.size();i++){
                                if (name_list.get(i).equals(entity.getManger_name())){

                                }
                            }
                            for (int i = 0;i<fslist.size();i++){
                                if (fslist.get(i).getId()==entity.getFs_id()){
                                    sp_jl_fs.setSelection(i);
                                }
                            }
                        }
                    }
                });

            }
        }).start();
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String a = getTime(new Date());
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    date2 =  formatter.parse(a);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
               if (tv_jll.getText().toString().equals("")){
                    Toast.makeText(JYAddJLActivity.this, "请输入交流量", Toast.LENGTH_SHORT).show();
                }else if (tv_pj.getText().toString().equals("")){
                    Toast.makeText(JYAddJLActivity.this, "请输入主任要求", Toast.LENGTH_SHORT).show();
                }else if (!"update".equals(getIntent().getStringExtra("tag"))&&"".equals(show_coor.getText().toString())){
                   Toast.makeText(JYAddJLActivity.this, "请选择合作客户", Toast.LENGTH_SHORT).show();
               }else{
                    add();
                }
            }
        });
    }
    private void setMessage() {
        add_jl.setText("修改交流");
        entity = GetExchange.exchangeEntity;
        tv_pj.setText(entity.getYijian());
        tv_jll.setText(entity.getJiaoliuliang());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date1 =  formatter.parse(entity.getBf_time());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void add() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                final JSONObject object = sc.storage(sp);
                try {
                    object.put("ABF01",fs_id);
                    object.put("KJA08",tv_jll.getText().toString());
                    object.put("KJA03",sp.getString("CID01",null));
                    object.put("KJA09",tv_pj.getText().toString());
                    if ("update".equals(getIntent().getStringExtra("tag"))){
                        object.put("addoredit","edit");
                        object.put("KJA01",entity.getId());
                        object.put("KXA01",entity.getCoor_id());
                    }else {
                        object.put("KJA04",sp.getString("CID03",null));
                        object.put("addoredit","add");
                        object.put("KXA01",coor_id);
                        object.put("KJA12",address);
                        object.put("KJA11",wd);
                        object.put("KJA10",jd);
                    }
                    object.put("CID03",sp.getString("CID03",null));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                final String result = NetWorkUtils.getCount(baseClass.addoredit_jl_URL,json);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        boolean b = false;
                        try {
                            Log.d("sss",result);
                           object1 = new JSONObject(result);
                            b = object1.getBoolean("ifsuccess");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (b){
                            finish();
                            if ("update".equals(getIntent().getStringExtra("tag"))){
                                Toast.makeText(JYAddJLActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(JYAddJLActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                            }
                        }else {
                            try {
                                msg=object1.getString("msg");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            if ("update".equals(getIntent().getStringExtra("tag"))){
                                Toast.makeText(JYAddJLActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                            }else {
                                if ("".equals(msg)) {
                                    if ("update".equals(getIntent().getStringExtra("tag"))) {
                                        Toast.makeText(JYAddJLActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(JYAddJLActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(JYAddJLActivity.this, msg, Toast.LENGTH_SHORT).show();
                                }
                            }


                        }
                    }
                });
            }
        }).start();
    }
    private void showPopupWindow() {
        View contentView = LayoutInflater.from(JYAddJLActivity.this).inflate(
                R.layout.popuwindoe_select_coor, null);

        mPopWindow = new PopupWindow(contentView);
        mPopWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        mPopWindow.setHeight( LinearLayout.LayoutParams.WRAP_CONTENT);

        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = contentView.getMeasuredWidth();    //  获取测量后的宽度
        final int popupHeight = contentView.getMeasuredHeight();  //获取测量后的高度
        int[] location = new int[2];
        edit_search = (EditText) contentView.findViewById(R.id.edit_seacher);
        btn_search = (Button) contentView.findViewById(R.id.btn_show);
        listView = (ListView) contentView.findViewById(R.id.btn_listview);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                coorname = coorlist.get(position).getDocking_name();
                coor_id = coorlist.get(position).getDocking_id();
                show_coor.setText(coorname);
                mPopWindow.dismiss();
            }
        });
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SC sc = new SC();
                        JSONObject object = sc.storage(sp);
                        try {
                            object.put("KXA02",edit_search.getText().toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String json = object.toString();
                        dockDao dockDao = new dockDaoImpl();
                        coorlist = dockDao.queryAllCoordinationMessage(baseClass.find_coordination_url + 1, json);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (coorlist==null){
                                    Toast.makeText(JYAddJLActivity.this, "搜索不到信息！！", Toast.LENGTH_SHORT).show();
                                }else {
                                    adapter = new CoorSelectAdapter(JYAddJLActivity.this,coorlist);
                                    listView.setAdapter(adapter);
                                }
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }
                }).start();
            }
        });
        img_coor_select.getLocationOnScreen(location);
        mPopWindow.setAnimationStyle(R.style.contextMenuAnim);
        mPopWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.pop_bg));
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);   //设置外部点击关闭ppw窗口
        mPopWindow.setFocusable(true);
        mPopWindow.update();
        mPopWindow.showAsDropDown(img_coor_select);
        backgroundAlpha(0.5f);
        mPopWindow.setOnDismissListener(new poponDismissListener());
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha= bgAlpha;
        getWindow().setAttributes(lp);
    }
    class poponDismissListener implements PopupWindow.OnDismissListener{

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
        }

    }
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            //获取定位结果
            StringBuffer sb = new StringBuffer(256);

            sb.append(location.getTime()+",");
            sb.append(location.getLocationDescribe()+",");// 位置语义化信息
            sb.append(location.getLatitude()+",");    //获取纬度信息
            sb.append(location.getLongitude());    //获取经度信息
            if (sb!=null) {
                str = sb.toString();
                String[] strs = str.split(",");
                jd = Double.parseDouble(strs[3]);
                wd = Double.parseDouble(strs[2]);
                address=strs[1];
//              sb=null;
            }
        }
    }
}
